package com.autonavi.yunda.yunji.core.utils;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

@SuppressWarnings({"unused", "StringOperationCanBeSimplified"})
public class CipherUtils {
    public static final String SIGN_TYPE_RSA = "RSA";
    public static final String SIGN_ALGORITHMS_SHA1 = "SHA1WithRSA";
    public static final String SIGN_ALGORITHMS_SHA256 = "SHA256WithRSA";
    public static final String SIGN_ALGORITHMS_MD5 = "MD5withRSA";

    /* RSA最大加密明文大小 */
    private static final int MAX_ENCRYPT_BLOCK = 117;
    /* RSA最大解密密文大小 */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * 加密
     */
    public static String encrypt(String data, String cipherType, String publicKey) throws Exception{
        if (SIGN_TYPE_RSA.equals(cipherType)) {
            Cipher cipher = Cipher.getInstance(cipherType);
            cipher.init(Cipher.ENCRYPT_MODE, getPublicKeyFromX509(cipherType, publicKey));
            int inputLen = data.getBytes().length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offset = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段加密
            while (inputLen - offset > 0) {
                if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
                }
                out.write(cache, 0, cache.length);
                i++;
                offset = i * MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptedData = out.toByteArray();
            out.close();
            // 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
            // 加密后的字符串
            return new String(Base64.getEncoder().encode(encryptedData));
        }

        return null;
    }

    /**
     * 解密
     */
    public static String decrypt(String data, String cipherType, String privateKey) throws Exception {
        if (SIGN_TYPE_RSA.equals(cipherType)) {
            Cipher cipher = Cipher.getInstance(cipherType);
            cipher.init(Cipher.DECRYPT_MODE, getPrivateKeyFromPkcs8(cipherType, privateKey));
            byte[] dataBytes = Base64.getDecoder().decode(data.getBytes());
            int inputLen = dataBytes.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offset = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段解密
            while (inputLen - offset > 0) {
                if (inputLen - offset > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
                }
                out.write(cache, 0, cache.length);
                i++;
                offset = i * MAX_DECRYPT_BLOCK;
            }
            byte[] decryptedData = out.toByteArray();
            out.close();
            // 解密后的内容
            return new String(decryptedData, StandardCharsets.UTF_8);
        }

        return null;
    }

    /**
     * 读取私钥
     *
     * @param signType 算法
     * @param signKey  密钥串
     * @return 私钥
     * @throws Exception exception
     */
    public static PrivateKey getPrivateKeyFromPkcs8(String signType, String signKey) throws Exception {
        if (signKey == null || signType == null || "".equals(signType)) {
            return null;
        }

        KeyFactory keyFactory = KeyFactory.getInstance(signType);
        byte[] encodedKey = signKey.getBytes();
        encodedKey = Base64.getDecoder().decode(encodedKey);
        return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
    }

    /**
     * 读取公钥
     *
     * @param signType 算法
     * @param signKey  密钥串
     * @return 公钥
     * @throws Exception exception
     */
    public static PublicKey getPublicKeyFromX509(String signType, String signKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance(signType);
        byte[] encodedKey = signKey.getBytes();
        encodedKey = Base64.getDecoder().decode(encodedKey);
        return keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
    }
}
